package com.urguxxi.springdemo.service.impl;
import com.urguxxi.springdemo.service.LoginService;
import com.urguxxi.springdemo.dto.ResultDTO;
import com.urguxxi.springdemo.entity.Admin;
import com.urguxxi.springdemo.mapper.AdminMapper;
import com.urguxxi.springdemo.exception.LoginExcetion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;

/**
 * 用户登录的实现类
 */
@Service
//注意用implements实现LoginService
public class LoginServiceImpl implements LoginService {
    //自动注入
    @Autowired
    private AdminMapper mapper;
    /**
     * 用户登录的业务层(方法)的实现
     * 中转接收请求
     * @param admin
     * @return
     */
    @Override
    public ResultDTO login(Admin admin, HttpSession session){
        //数据校验
        //查询数据
        Admin dbAdmin = mapper.findByName(admin.getAdminName());
        if (dbAdmin==null){
//            return new ResultDTO(1001,"The admin doesn't exist.");
            throw new LoginExcetion(1001,"The admin doesn't exist.");
        }
        //判断状态
        if (dbAdmin.getAdminStatus()!=null && dbAdmin.getAdminStatus().equals(0)){
//            return new ResultDTO(1001,"The admin is locked.Please contact the root-admin!");
            throw new LoginExcetion(1001,"The admin is locked.Please contact the root-admin!");
        }
        //判断密码是否正确
        if(!dbAdmin.getAdminPwd().equals(admin.getAdminPwd())){
//            return new ResultDTO(1001,"The wrong pwd!");
            throw  new LoginExcetion(1001,"The wrong pwd!");
        }

        //登陆成功，将用户信息放入session中
        session.setAttribute("adminName",admin.getAdminName());
        //改变登录时间
        dbAdmin.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        mapper.update(dbAdmin);

        //注意最后的返回
        return  new ResultDTO(200,"Success!");
    }

}
